package com.esd.crm.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.esd.crm.Constants;

@Component
public class LogInterceptor implements HandlerInterceptor {

	private static final Logger logger = LogManager.getLogger(LogInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		//String requestURI = httpServletRequest.getRequestURI();
		//logger.info("----------------过滤器正在处理-----------------");
		//logger.info("该请求为:" + requestURI);
		Object obj = httpServletRequest.getSession().getAttribute(Constants.USER_ID);
		if (obj == null) {
			PrintWriter out = null;
			try {
				out = httpServletResponse.getWriter();
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("window.top.location.href='");
				builder.append("/login");
				builder.append("';");
				builder.append("</script>");
				out.print(builder.toString());
				out.close();
				return false;
			} catch (IOException e) {
				logger.error(e.getMessage());
			} finally {
				if (out != null) {
					out.close();
				}
			}

		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}
